/**
 * Copyright (C) 2008+ Spark Zheng
 *
 * test/test_sheap.c
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "heap.h"

#define CAPACITY	11

static void dump_fn(void *data);
static int compare_fn(const void *one, const void *two);

static void dump_fn(void *data)
{
	fprintf(stdout, "    %d\t", *(int *)data);
	return;
}

static int compare_fn(const void *one, const void *two)
{
	int a = *((const int *) one);
	int b = *((const int *) two);

	if (a == b) {
//		fprintf(stderr, "EQ, a = %d, b = %d\n", a, b);
		return 0;
	} else if (a < b) {
//		fprintf(stderr, "LT, a = %d, b = %d\n", a, b);
		return 1;
	} else {
//		fprintf(stderr, "GT, a = %d, b = %d\n", a, b);
		return -1;
	}
}

#define TEST_LOOP_NR	1000

int main(int argc, char *argv[])
{
	sheap_t *sheap = simple_heap_init(CAPACITY, compare_fn, NULL);
	if (sheap == NULL) {
		fprintf(stderr, "simple_heap_init error.\n");
		return -1;
	}

	int ret = 0;
	int i = 0;
	int data[TEST_LOOP_NR];

	srand(time(NULL));
	for (; i < TEST_LOOP_NR; i++) {
		data[i] = rand() % 100;
	}

	for (i = 0; i < TEST_LOOP_NR; i++) {
		ret = simple_heap_push(sheap, (void *)&data[i]);
		if (ret < 0) {
			fprintf(stderr, "simple_heap_push [%d:%d] error[%d].\n", data[i], i, ret);
			goto end;
		}
		//simple_heap_dump(sheap, dump_fn);
	}

	fprintf(stdout, "\n\n");
	simple_heap_dump(sheap, dump_fn);
	fprintf(stdout, "\n\n");

	/*
	for (i = 0; i < TEST_LOOP_NR / 2; i++) {
		void *result = NULL; 
		ret = simple_heap_pop(sheap, &result);
		if (ret < 0) {
			fprintf(stderr, "simple_heap_pop [%d] error[%d].\n", i, ret);
			goto end;
		} else {
			simple_heap_dump(sheap, dump_fn);
			fprintf(stdout, "simple_heap_pop [%d] val[%d].\n\n", i, *((int *)result));
		}
	}

	ret = simple_heap_delete(sheap, &sheap->heap_nodes[TEST_LOOP_NR/2-1]);
	if (ret < 0) {
		fprintf(stderr, "simple_heap_delete [%d] error[%d].\n", TEST_LOOP_NR/2-1, ret);
		goto end;
	}
	*/

	fprintf(stdout, "\n\n");
	simple_heap_dump(sheap, dump_fn);
	fprintf(stdout, "\n\n");

	int *result[TEST_LOOP_NR];
	ret = simple_heap_sort(sheap, (void **)result, TEST_LOOP_NR);
	if (ret < 0) {
		fprintf(stderr, "simple_heap_sort error[%d].\n", ret);
		goto end;
	}
	for (i = 0; i < ret; i++) {
		fprintf(stdout, "%d\n", *(result[i]));
	}
	fprintf(stdout, "\n\n");
	simple_heap_dump(sheap, dump_fn);
	fprintf(stdout, "\n\n");

end:
	simple_heap_exit(sheap);
	return ret;
}
